import 'dart:async';

import 'package:flutter_wan_android/data/user/user_table_struct.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';

/// sqlite数据库
class DataBaseStorage {

  static final DataBaseStorage _instance = DataBaseStorage._();

  factory DataBaseStorage(){
    return _instance;
  }

  DataBaseStorage._();

  Database? _db;

  /// 懒加载访问
  Future<Database> get database async {
    if (_db != null) return _db!;
    _db = await _initDB();
    return _db!;
  }

  Future<Database> _initDB() async {
    var dic = await getApplicationDocumentsDirectory();
    var dbName = "app_db.db";
    var path = join(dic.path, dbName); // 数据库目录
    var version = 1;
    var readOnly = false; // 只读 默认false
    var singleInstance = true; // 单例打开数据库 默认 true
    return await openDatabase(path, version: version,
        onConfigure: _onConfigure,
        onCreate: _onCreate,
        onUpgrade: _onUpgrade,
        onDowngrade: _onDowngrade,
        onOpen: _onOpen,
        readOnly: readOnly,
        singleInstance: singleInstance);
  }

  /// 最先调用的的callback，在打开数据库之前调用
  FutureOr<void> _onConfigure(Database db) async {

  }

  ///当数据库第一次创建时调用,在此建表
  FutureOr<void> _onCreate(Database db, int version) async {
      db.execute(UserTableStruct.createTableSql);
  }

  /// 每次打开数据库之后都会调用
  FutureOr<void> _onOpen(Database db) async {

  }

  /// 数据库升级调用
  FutureOr<void> _onUpgrade(Database db, int oldVersion, int newVersion) async {

  }

  /// 数据库降级（不明白为什么会有这种场景 zzz）
  FutureOr<void> _onDowngrade(Database db, int oldVersion, int newVersion) async {

  }

  FutureOr<void> close() async {
    _db?.close();
  }

}